package com.hmjk.health.family;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.NetService;
import com.hmjk.health.setting.SettingsConstants;
import com.hmjk.health.util.FA_DATA;
import com.hmjk.health.util.FMEM_DATA;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class FamilyDetailActivity extends Activity implements OnClickListener{
	private final String TAG = FamilyDetailActivity.class.getSimpleName();
	
	private HealthApp mApp = null;
	
	private FA_DATA mCurFA;

	private TextView mFaName;
	private TextView mFaAddr;
	private TextView mFaPhone;
	private TextView mAdminName, mCreatorName;
	private Button editBut = null;
	private String admin_name = null;
	private String creator_name = null;
	
	private String localFamilyName = "";
	private String localFamilyAddr = "";
	private String localFamilyPhone = "";
	
	private boolean needRefresh = true;
	private final int RESULT_CODE = 1;
	
	private long uptime = 0;

	private void logd(String info){
		Log.d(TAG,info);
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.familydetail_activity);
        mApp = (HealthApp)getApplication();
        
        SharedPreferences pref = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
		String fid = pref.getString(SettingsConstants.KEY_FA_FID, "");
		mCurFA = new FA_DATA();
		mCurFA.id = fid;
		
        ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		editBut = (Button)findViewById(R.id.edit);
		editBut.setOnClickListener(this);
		
		mFaName = (TextView)findViewById(R.id.familyname);
		mFaAddr = (TextView)findViewById(R.id.familyaddr);
		mFaPhone = (TextView)findViewById(R.id.familyphone);

		mAdminName = (TextView)findViewById(R.id.admin_name);
		mCreatorName = (TextView)findViewById(R.id.creator_name);
		
		needRefresh = true;
	}
	
	@Override
	public void onResume(){
		logd("onResume");
		super.onResume();
		
		checkFamilyDetail();
		retrieveFamilyListData();
		retrieveFamilyMemberData();
		
		updateFamilyDetail();
		if((mCurFA.admin == false) && (mCurFA.creator == false)){
			editBut.setVisibility(View.INVISIBLE);
		}else {
			editBut.setVisibility(View.VISIBLE);
		}
	}
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case HealthApp.MSG_NET_RESPONSE:{
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				boolean canceled = b.getBoolean("canceled", false);
				if(stamp.startsWith("GET_FAMILY_DETAIL")){
					String sjson = b.getString("json");
					if(sjson != null){
						mApp.dismissWaiting();
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									// TODO add success
									JSONObject recdata = json.getJSONObject("recdata");
									if(recdata != null){
										if(recdata.has("familyname")){
											localFamilyName = recdata.getString("familyname").trim();
										}
										if(recdata.has("familyaddress")){
											localFamilyAddr = recdata.getString("familyaddress").trim();
										}
										if(recdata.has("familyphoneno")){
											localFamilyPhone = recdata.getString("familyphoneno").trim();
										}
										updateFamilyDetail();
									}
									return;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}break;
			}
		}
	};
	
	private void checkFamilyDetail(){
		if(needRefresh == false)
			return;
		mApp.showWaitting(this, null);
		Intent si = new Intent(this, NetService.class);
		si.setAction(NetService.GET_FAMILY_DETAIL);
		si.putExtra("uid", mApp.getUID());
		si.putExtra("fid", mCurFA.id);
		
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_FAMILY_DETAIL" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp, mHandler);
		startService(si);
		needRefresh = false;
	}

	
	private void updateFamilyDetail(){
		if((localFamilyName == null) || localFamilyName.isEmpty()){
			mFaName.setText(getResources().getString(R.string.family_none));
		}else {
			mFaName.setText(localFamilyName);
		}
		
		if((localFamilyAddr == null) || localFamilyAddr.isEmpty()){
			mFaAddr.setText(getResources().getString(R.string.family_none));
		}else {
			mFaAddr.setText(localFamilyAddr);
		}
		
		if((localFamilyPhone == null) || localFamilyPhone.isEmpty()){
			mFaPhone.setText(getResources().getString(R.string.family_none));
		}else {
			mFaPhone.setText(localFamilyPhone);
		}
		
		if(mCurFA.creator){
			mCreatorName.setText(R.string.Me);
		}else{
			if(creator_name != null){
				mCreatorName.setText(creator_name);
			}else{
				mCreatorName.setText("!");
			}
		}
		
		if(mCurFA.admin){
			mAdminName.setText(R.string.Me);
		}else{
			if(admin_name != null){
				mAdminName.setText(admin_name);
			}else{
				mAdminName.setText(R.string.family_none);
			}
		}
	}

	private void retrieveFamilyListData(){
		JSONObject fajson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYLIST, null);
		if(fajson != null){
			try {
				long t = fajson.getLong("uptime");
				uptime = Math.max(uptime, t);
				JSONArray ar = fajson.getJSONArray("array");
				int len = ar.length();
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					FA_DATA d = new FA_DATA();
					d.id = e.getString("fid");
					if(mCurFA.id.equals(d.id)){			
					d.name = e.getString("name");
					
					d.status = e.getString("status");
					String b = e.getString("build");
					if(b.equals("1")){
						d.creator = true;
					}
					
					String a = e.getString("admin");
					if(a.equals("1")){
						d.admin = true;
					}
					
					
					mCurFA.name = d.name;
					mCurFA.index = i;
					mCurFA.status = d.status;
					mCurFA.admin = d.admin;
					mCurFA.creator = d.creator;
					break;
					}
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void retrieveFamilyMemberData(){
		admin_name = null;
		creator_name = null;
		
		JSONObject memjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYMEMBER, null);
		if(memjson != null){
			try {
				long t = memjson.getLong("uptime");
				uptime = Math.max(uptime, t);
				JSONArray ar = memjson.getJSONArray("array");
				int len = ar.length();
				for(int i = 0; i < len; i++){
					
					JSONObject e = ar.getJSONObject(i);
					FMEM_DATA d = new FMEM_DATA();
					
					d.fid = e.getString("fid");
					
					if(d.fid.equals(mCurFA.id)){
						String b = e.getString("build");
						if(b.equals("1")){
							creator_name = e.getString("name");	
						}
						
						String a = e.getString("admin");
						if(a.equals("1")){
							admin_name = e.getString("name");
						}
					}
					
					if((admin_name != null) && (creator_name != null)){
						break;
					}
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		
		case R.id.edit:{
			Intent i = new Intent(this, FamilyDetailEditorActivity.class);
			i.putExtra("fid", mCurFA.id);
			i.putExtra("name", localFamilyName);
			i.putExtra("address", localFamilyAddr);
			i.putExtra("mobile", localFamilyPhone);
			startActivityForResult(i, RESULT_CODE);
		}break;
		
		}
		
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		if((requestCode == RESULT_CODE) && (resultCode == RESULT_OK)){
			needRefresh = true;
		}
	}

}
